package com.mf.ShardingAlgorithm;

import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;

import java.util.Collection;

public class CustomTableRule implements StandardShardingAlgorithm<String> {
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<String> preciseShardingValue) {
        //返回插入数据的列值
        String dm = preciseShardingValue.getValue();
        return setTableName(dm);
    }

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<String> rangeShardingValue) {
        System.out.println("collection:" + collection.toString());
        System.out.println("rangeShardingValue:" + rangeShardingValue.toString());
        return null;

    }

    // 根据股票代码分配到不同的表中
    public String setTableName(String dm) {
        // 前缀
        String prefix = "t_code_history_";
        final int numberDm = Integer.parseInt(dm);
        String tableName = prefix;
        if (dm.startsWith("000")) {
            tableName += getIndex(numberDm, 11, 1);
        } else if (dm.startsWith("001")) {
            tableName +=  getIndex(numberDm, 3, 13);
        } else if (dm.startsWith("002")) {
            tableName +=  getIndex(numberDm, 14, 27);
        } else if (dm.startsWith("003")) {
            tableName +=  getIndex(numberDm, 2, 29);
        } else if (dm.startsWith("300")) {
            tableName +=  getIndex(numberDm, 15, 44);
        } else if (dm.startsWith("301")) {
            tableName +=  getIndex(numberDm, 10, 54);
        } else if (dm.startsWith("600")) {
            tableName +=  getIndex(numberDm, 16, 70);
        } else if (dm.startsWith("601")) {
            tableName +=  getIndex(numberDm, 4, 74);
        } else if (dm.startsWith("603")) {
            tableName +=  getIndex(numberDm, 11, 85);
        } else if (dm.startsWith("605")) {
            tableName +=  getIndex(numberDm, 2, 87);
        } else if (dm.startsWith("688") || dm.startsWith("689")) {
            tableName +=  getIndex(numberDm, 13, 100);
        }

        return tableName;
    }

    /**
     * 根据给定的条件计算并返回一个索引值。
     * 该方法主要用于根据一个数字对其余数进行计算，以确定在特定循环逻辑中的位置。
     *
     * @param numberDm  输入的数字，用于计算余数。
     * @param remainder 除数，用于计算numberDm的余数。
     * @param count     一个偏移量，用于在余数为0时调整返回的索引值。
     * @return 计算得到的索引值，考虑了余数为0的特殊情况并进行了调整。 13 100
     */
    private Integer getIndex(Integer numberDm, int remainder, int count) {
        // 计算numberDm除以remainder的余数
        int number = numberDm % remainder;
        // 如果余数为0，直接返回0，否则进行进一步计算
        if (number == 0) {
            return number + count - 1;
        }
        // 在余数不为0的情况下，返回调整后的索引值
        return number + count - 1;
    }

}